package hu.cskassai.sad.business.helper;

import hu.cskassai.sad.business.vo.DynamicClassLoaderVO;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class DynamicFileClassLoader {
	
	public static <V> V loadInstance(DynamicClassLoaderVO vo){
		Class<?> clazz = loadClass(vo);
		Object instance = null;
		try {
			instance = clazz.newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		@SuppressWarnings("unchecked")
		V castedInstance = (V)instance;
		//TODO - hibakezeles
		return castedInstance;
		
	}
	
	public static Class<?> loadClass(final DynamicClassLoaderVO vo) {
		URL url = null;
		try {
			 File f = new File(vo.getUrl());
          url = f.toURL();
		} catch (final MalformedURLException e) {
			throw new RuntimeException("The url path has unknown protocol", e);
		}
		final URL[] us = { url };
		final ClassLoader classLoader = new URLClassLoader(us);
		Class<?> clazz = null;
		try {
			clazz = classLoader.loadClass(vo.getFullQualifiedName());
		} catch (final ClassNotFoundException e) {
			throw new RuntimeException("There is no class file defined this parameters: url = " + vo.getUrl()
				+ "; full qualified name = " + vo.getFullQualifiedName(), e);
		}
		
		return clazz;
	}
	
}
